#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import time

from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility
from extension.test_logic.RequestBase import RequestBase


class REDFISH_COMPUTER_001(Case):
    """
        Name:
            REDFISH_COMPUTER_001
        Label:
            关闭服务器
        PreCondition:
            BMC web service normal
        TestStep:
            1) post https://BMC_IP/redfish/v1/Systems/{System_id}/Actions/ComputerSystem.Resetbody里添加{"ResetType":ForceOff"}
        ExpectedResult:
            A) 执行响应码为200,机器关机
        Parameters:

        Author:
            baixin liuya
        Last Modified:

        Remark:

    """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.bmc_host = self.device_dut.get_host(host_type=HostType.BMC)
        self.bmc_ip = self.bmc_host.local_ip
        self.bmc_user = self.bmc_host.username
        self.bmc_pwd = self.bmc_host.password

        self.logger.info("获取Token")
        self.request = RequestBase(self.bmc_ip, self.bmc_user, self.bmc_pwd)
        return_code, session_id = self.request.create_session()
        self.assertIsNotNone(return_code)
        self.session_id = session_id

    # 测试步骤
    def procedure(self):
        self.log_step("Step1: 查询服务器system id")
        url = "/redfish/v1/Systems"
        resp = self.request.get(url)
        if resp[0] != 200:
            self.assertIsNotNone(None, f"查询服务器system_id失败：\nrc:{resp[0]}\n{resp[1]}")
        count = resp[1]['Members@odata.count']
        member = resp[1]['Members'][0]['@odata.id']
        self.logger.info(f"Members@odata.count: {count}, Members: {member}")

        self.log_step("Step2: 查询服务器电源状态")
        url = member
        resp = self.request.get(url)
        if resp[0] != 200:
            self.assertIsNotNone(None, f"查询服务器system_id失败：\nrc:{resp[0]}\n{resp[1]}")
        power_state = resp[1]['PowerState']
        self.logger.info(f"服务器电源状态： {power_state}")

        url = f"{url}/Actions/ComputerSystem.Reset"
        self.logger.info(f"URL：{url}")
        if power_state == "Off":
            self.log_step("Step3: 服务器上电")
            resp = self.request.post(url=url, params={"ResetType": "On"})
            if resp[0] != 200:
                self.assertIsNotNone(None, f"服务器上电失败：\nrc:{resp[0]}\n{json.dumps(resp[1], indent=4)}")
            self.logger.info(json.dumps(resp[1], indent=4))
            time.sleep(30)
            self.log_step("Step4: 关闭服务器")
            resp = self.request.post(url=url, params={"ResetType": "ForceOff"})
            if resp[0] != 200:
                self.assertIsNotNone(None, f"关闭服务器失败：\nrc:{resp[0]}\n{json.dumps(resp[1], indent=4)}")
            self.logger.info(json.dumps(resp[1], indent=4))
        else:
            self.log_step("Step3: 关闭服务器")
            resp = self.request.post(url=url, params={"ResetType": "ForceOff"})
            if resp[0] != 200:
                self.assertIsNotNone(None, f"关闭服务器失败：\nrc:{resp[0]}\n{json.dumps(resp[1], indent=4)}")
            self.logger.info(json.dumps(resp[1], indent=4))

        self.logger.info("服务器恢复上电")
        resp = self.request.post(url=url, params={"ResetType": "On"})
        if resp[0] != 200:
            self.assertIsNotNone(None, f"服务器恢复上电失败：\nrc:{resp[0]}\n{json.dumps(resp[1], indent=4)}")

        self.logger.info("睡眠300s， 等待服务器状态恢复")
        time.sleep(300)

    # 测试结束后恢复环境
    def post_test_case(self):
        resp = self.request.delete_session(self.session_id)
        self.assertIsNotNone(resp[0], "清除Token失败")
        self.logger.info("清除Token成功")
